package com.soloyogame.anitoys.center.web.controller.manage.business;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.awt.image.CropImageFilter;
import java.awt.image.FilteredImageSource;
import java.awt.image.ImageFilter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.qiniu.util.StringMap;
import com.soloyogame.anitoys.center.web.controller.BaseController;
import com.soloyogame.anitoys.center.web.util.LoginUserHolder;
import com.soloyogame.anitoys.center.web.util.RequestHolder;
import com.soloyogame.anitoys.db.bean.User;
import com.soloyogame.anitoys.db.commond.Business;
import com.soloyogame.anitoys.db.commond.UserInfo;
import com.soloyogame.anitoys.db.page.PagerModel;
import com.soloyogame.anitoys.service.BusinessService;
import com.soloyogame.anitoys.service.UserInfoService;
import com.soloyogame.anitoys.util.MD5;
import com.soloyogame.anitoys.util.qiniu.QiniuUploadManager;
import com.soloyogame.anitoys.util.qiniu.TestConfig;

/**
 * 折扣券管理 xukezhen
 * 
 */
@Controller
@RequestMapping("/manage/business/")
public class BusinessAction extends BaseController<Business> {
	private static final org.slf4j.Logger logger = LoggerFactory
			.getLogger(BusinessAction.class);
	private static final long serialVersionUID = 1L;

	@Autowired
	private BusinessService businessService;

	@Autowired
	private UserInfoService userInfoService;

	private static final String page_toList = "/manage/business/businessList";
	private static final String page_toAdd = "/manage/business/businessAdd";
	private static final String page_toEdit = "/manage/business/businessEdit";

	private BusinessAction() {
		super.page_toList = page_toList;
		super.page_toAdd = page_toAdd;
		super.page_toEdit = page_toEdit;
	}

	public BusinessService getBusinessService() {
		return businessService;
	}

	public void setBusinessService(BusinessService businessService) {
		this.businessService = businessService;
	}

	public UserInfoService getUserInfoService() {
		return userInfoService;
	}

	public void setUserInfoService(UserInfoService userInfoService) {
		this.userInfoService = userInfoService;
	}

	@Override
	public BusinessService getService() {
		return businessService;
	}

	/**
	 * 新增商家信息
	 * 
	 * @return
	 * @throws Exception
	 */

	@RequestMapping(value = "insertBusiness", method = RequestMethod.POST)
	public String insertBusiness(HttpServletRequest request,
			@ModelAttribute("e") Business e, RedirectAttributes flushAttrs,
			@RequestParam(value = "fileName") MultipartFile imageFile,
			@RequestParam(value = "bannerName") MultipartFile bannerFile,
			@RequestParam(value = "x") String x,
			@RequestParam(value = "y") String y,
			@RequestParam(value = "w") String w,
			@RequestParam(value = "h") String h) throws Exception {
		User user = LoginUserHolder.getLoginUser();

		logger.debug("**********************************************" + x + y
				+ w + h);
		e.setUserId(user.getId());
		logger.debug(e.getUsername());
		logger.debug(e.getPassword());
		// 新增商家用户
		UserInfo uInfo = new UserInfo();
		uInfo.setUsername(e.getUsername());
		uInfo.setPassword(MD5.md5(e.getPassword()));
		uInfo.setCreateAccount(user.getUsername());
		uInfo.setStatus("y");
		uInfo.setRid("1");
		int numId = userInfoService.insertByBusiness(uInfo);

		logger.debug("新增商家联动生成商家用户，ID=" + numId);

		logger.debug("e.getMaxPicture():" + e.getMaxPicture());
		logger.debug("e.getTheFilePath():" + e.getTheFilePath());
		logger.debug("e.getBannerPicture()：" + e.getBannerPicture());
		String src2 = "";
		String realPath = request.getSession().getServletContext()
				.getRealPath("/");
		logger.debug("realPath:" + realPath);
		String resourcePath = "manage/business/img/";
		if (imageFile != null) {
			Date date = new Date(System.currentTimeMillis());
			String strDate = new SimpleDateFormat("yyyyMMddhhmmss")
					.format(date);
			int random = (int) (Math.random() * 99);
			String imageName = strDate + random; // 以系统时间来随机的创建图片文件名
			File dir = new File(realPath + resourcePath);
			if (!dir.exists()) {
				dir.mkdirs();
			}
			File file = new File(dir, imageName + "_src.jpg");
			imageFile.transferTo(file);// 转存文件
			// logger.debug("&&&&&&&&&&&&&开始裁剪图片&&&&&&&&&&&&&");
			// int imageX = 0;
			// int imageY = 0;
			// int imageH = 20;
			// int imageW = 20;
			// if(!StringUtils.isEmpty(x))
			// imageX = (int)Double.parseDouble(x.replace(" ",""));
			// if(!StringUtils.isEmpty(y))
			// imageY = (int)Double.parseDouble(y.replace(" ",""));
			// if(!StringUtils.isEmpty(h))
			// imageH = (int)Double.parseDouble(h.replace(" ",""));
			// if(!StringUtils.isEmpty(w))
			// imageW = (int)Double.parseDouble(w.replace(" ",""));
			// String srcImagePath = realPath + resourcePath+imageName;
			// imgCut(srcImagePath,imageX,imageY,imageW,imageH);
			// logger.debug("&&&&&&&&&&&&&结束裁剪图片&&&&&&&&&&&&&");
			// File f = new File(srcImagePath+"_cut.jpg");//截取后的图片
			src2 = "manage/business/img/" + imageName + ".jpg";// String
																// expectKey =
																// "attached/image/head/"+saveName+"_cut.jpg";
			// src2 = "manage/business/img/"+imageName+"_cut.jpg";
			String token = TestConfig.testAuth.uploadToken(TestConfig.bucket,
					src2);
			StringMap params = new StringMap().put("x:foo", "foo_val");
			// QiniuUploadManager.uploadFile(f, src2, token, params);//上传截取后的图片
			QiniuUploadManager.uploadFile(file, src2, token, params);
			e.setMaxPicture(src2);
		}
		// banner图片地址 add by zhangjing
		String bannerPath = "";
		if (bannerFile != null
				&& (e.getBannerPicture().indexOf(resourcePath) < 0)) {
			Date date = new Date(System.currentTimeMillis());
			String strDate = new SimpleDateFormat("yyyyMMddhhmmss")
					.format(date);
			int random = (int) (Math.random() * 99);
			String imageName = strDate + random; // 以系统时间来随机的创建图片文件名
			File dir = new File(realPath + resourcePath);
			if (!dir.exists()) {
				dir.mkdirs();
			}
			File file = new File(dir, imageName + ".jpg");
			bannerFile.transferTo(file);

			bannerPath = "manage/business/img/" + imageName + ".jpg";//
			String token = TestConfig.testAuth.uploadToken(TestConfig.bucket,
					bannerPath);
			StringMap params = new StringMap().put("x:foo", "foo_val");
			QiniuUploadManager.uploadFile(file, bannerPath, token, params);
		} else {
			bannerPath = e.getBannerPicture();
			logger.debug("没有banner图片没有banner图片没有banner图片没有banner图片没有banner图片");
		}
		e.setBannerPicture(bannerPath);
		e.setUserId(numId + "");

		// 修改商家
		int busNum = getService().insert(e);
		insertAfter(e);

		// 修改商家用户
		UserInfo updInfo = new UserInfo();
		updInfo.setId(numId + "");
		updInfo.setUpdateAccount(user.getUsername());
		updInfo.setBusinessId(busNum);

		userInfoService.update(updInfo);

		addMessage(flushAttrs, "操作成功！");
		return "redirect:selectList";
	}

	/**
	 * 根据ID禁用当前的商家
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "disableByID", method = RequestMethod.POST)
	@ResponseBody
	public String disableByID(String id, int status, int regionID, int sortOrder)
			throws Exception {
		if (StringUtils.isBlank(id)) {
			throw new NullPointerException("参数不正确！");
		}
		Business e = new Business();
		e.setId(id);
		e.setStatus(status);
		e.setRegionID(regionID);
		e.setSortOrder(sortOrder);
		businessService.update(e);
		// return "redirect:selectList?type=Y";
		return String.valueOf(true);
	}

	/**
	 * 根据ID查询详情
	 * @return
	 * @throws Exception
	 */
	@Override
	@RequestMapping("toEdit")
	public String toEdit(@ModelAttribute("e") Business e, ModelMap model)throws Exception 
	{
		if (StringUtils.isBlank(e.getId())) 
		{
			throw new NullPointerException("非法请求！");
		}
		String id = RequestHolder.getRequest().getParameter("id");
		//String aaa =RequestHolder.getRequest().getParameter("pager.offset");
		String type = RequestHolder.getRequest().getParameter("type");
		logger.debug("id:+=====" + id);
		//logger.debug(e.getId()+"<>"+e.getStartDates()+"<>"+e.getEndDates()+"<>"+type+"<>"+e.getType()+"<>"+aaa);
		type = e.getType();
		Business eQry = e;
		e = getService().selectOne(e);
		if ("p".equals(type)) 
		{
			Business eInfo = new Business();
			eInfo.setId(e.getId());
			eInfo.setStartDates(eQry.getStartDates());
			eInfo.setEndDates(eQry.getEndDates());
			int offset = 0;// 分页偏移量
			logger.debug(RequestHolder.getRequest()
					.getParameter("pager.offset")
					+ "<>"
					+ (RequestHolder.getRequest().getParameter("pager.offset") != null));
			if (RequestHolder.getRequest().getParameter("pager.offset") != null)
			{
				offset = Integer.parseInt(RequestHolder.getRequest().getParameter("pager.offset"));
			}
			if (offset < 0) 
			{
				offset = 0;
			}
			eInfo.setOffset(offset);
			PagerModel pager = getService().selectBusinessDetailsList(eInfo);
			if (pager == null) 
			{
				pager = new PagerModel();
			}
			// 计算总页数
			pager.setPagerSize((pager.getTotal() + pager.getPageSize() - 1)
					/ pager.getPageSize());

			pager.setPagerUrl("toEdit");
			model.addAttribute("pager", pager);
		}
		e.setType(type);
		e.setStartDates(eQry.getStartDates());
		e.setEndDates(eQry.getEndDates());

		model.addAttribute("e", e);
		return page_toEdit;
	}

	/**
	 * 修改商家信息
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "deposit", method = RequestMethod.POST)
	public String updateBusiness(HttpServletRequest request,
			@ModelAttribute("e") Business e, RedirectAttributes flushAttrs,
			@RequestParam(value = "fileName") MultipartFile imageFile,
			@RequestParam(value = "bannerName") MultipartFile bannerFile)
			throws Exception {
		logger.debug("e.getMaxPicture():::" + e.getMaxPicture());
		logger.debug("e.getBannerPicture():::" + e.getBannerPicture());

		String src2 = "";

		String realPath = request.getSession().getServletContext()
				.getRealPath("/");
		logger.debug("realPath:" + realPath);
		String resourcePath = "manage/business/img/";
		if (e.getMaxPicture() != null && !"".equals(e.getMaxPicture())) {
			if (imageFile != null
					&& (e.getMaxPicture().indexOf(resourcePath) < 0)) {
				Date date = new Date(System.currentTimeMillis());
				String strDate = new SimpleDateFormat("yyyyMMddhhmmss")
						.format(date);
				int random = (int) (Math.random() * 99);
				String imageName = strDate + random; // 以系统时间来随机的创建图片文件名

				File dir = new File(realPath + resourcePath);
				if (!dir.exists()) {
					dir.mkdirs();
				}
				File file = new File(dir, imageName + ".jpg");
				imageFile.transferTo(file);

				src2 = "manage/business/img/" + imageName + ".jpg";// String
																	// expectKey
																	// =
																	// "attached/image/head/"+saveName+"_cut.jpg";
				String token = TestConfig.testAuth.uploadToken(
						TestConfig.bucket, src2);
				StringMap params = new StringMap().put("x:foo", "foo_val");
				QiniuUploadManager.uploadFile(file, src2, token, params);

			} else {
				src2 = e.getMaxPicture();
			}
		}

		logger.debug("src2:" + src2);
		e.setMaxPicture(src2);

		// banner图片地址 add by zhangjing
		String bannerPath = "";
		if (StringUtils.isNotBlank(e.getBannerPicture())) {
			if (bannerFile != null
					&& (e.getBannerPicture().indexOf(resourcePath) < 0)) {
				Date date = new Date(System.currentTimeMillis());
				String strDate = new SimpleDateFormat("yyyyMMddhhmmss")
						.format(date);
				int random = (int) (Math.random() * 99);
				String imageName = strDate + random; // 以系统时间来随机的创建图片文件名
				File dir = new File(realPath + resourcePath);
				if (!dir.exists()) {
					dir.mkdirs();
				}
				File file = new File(dir, imageName + ".jpg");
				bannerFile.transferTo(file);

				bannerPath = "manage/business/img/" + imageName + ".jpg";//
				String token = TestConfig.testAuth.uploadToken(
						TestConfig.bucket, bannerPath);
				StringMap params = new StringMap().put("x:foo", "foo_val");
				QiniuUploadManager.uploadFile(file, bannerPath, token, params);
			} else {
				bannerPath = e.getBannerPicture();
			}
		}
		e.setBannerPicture(bannerPath);

		businessService.update(e);
		addMessage(flushAttrs, "操作成功！");
		return "redirect:selectList";
	}

	/**
	 * 唯一性检查-商家排序
	 * 
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "uniqueCode", method = RequestMethod.POST)
	@ResponseBody
	public String uniqueCode(Business e) throws IOException {
		logger.error("unique code = " + e.toString());
		if (e.getSortOrder() != 0) {
			Business business = new Business();
			business.setSortOrder(e.getSortOrder());
			business = businessService.selectOne(business);

			if (business == null) {
				// 数据库中部存在此编码
				return "{\"ok\":\"编码可以使用!\"}";
			} else {
				if (!"0".equals(e.getSortOrder())) {
					logger.debug("e.getId():" + e.getId() + "<>"
							+ StringUtils.isNotBlank(e.getId()));
					logger.debug("business.getId():" + business.getId()
							+ "<StringUtils.trimToEmpty(e.getId())>"
							+ StringUtils.trimToEmpty(e.getId()));
					// logger.debug((StringUtils.isNotBlank(e.getId()) &&
					// StringUtils.trimToEmpty(e.getId()).equals(business.getId())));

					if (StringUtils.isNotBlank(e.getId())
							&& StringUtils.trimToEmpty(e.getId()).equals(
									business.getId())) {
						// update操作，又是根据自己的编码来查询的，所以当然可以使用啦
						return "{\"ok\":\"编码可以使用!\"}";
					} else {
						// 当前为insert操作，但是编码已经存在，则只可能是别的记录的编码
						return "{\"error\":\"编码已经存在!\"}";
					}
				} else {
					// 为“0”不进行排序，所以当然可以使用
					return "{\"ok\":\"编码可以使用!\"}";
				}
			}
		} else {
			return "{\"ok\":\"编码可以使用!\"}";
		}
	}

	/**
	 * 唯一性检查-商家账号名称
	 * 
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "uniqueUsername", method = RequestMethod.POST)
	@ResponseBody
	public String uniqueUsername(Business e) throws IOException {
		logger.error("unique username = " + e.getUsername());
		if (!"".equals(e.getUsername())) {
			UserInfo uInfo = new UserInfo();
			uInfo.setUsername(e.getUsername());
			UserInfo u = userInfoService.selectOne(uInfo);

			if (u == null) {
				// 数据库中部存在此商家账号
				return "{\"ok\":\"账号可以使用!\"}";
			} else {
				// 商家账号已经存在
				return "{\"error\":\"账号已经存在!\"}";
			}
		} else {
			return "{\"error\":\"账号不能为空!\"}";
		}
	}

	/**
	 * 唯一性检查-大图地址名称
	 * 
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "uniqueImage", method = RequestMethod.POST)
	@ResponseBody
	public String uniqueImage(Business e) throws IOException {
		logger.error("unique code = " + e.getMaxPicture());
		if (StringUtils.isNotBlank(e.getMaxPicture())) {
			String src = RequestHolder.getRequest().getRealPath("")
					+ "\\manage\\business\\img\\" + e.getMaxPicture();

			File file = new File(src);

			if (!file.exists()) {
				// 上传的文件名称不存在
				return "{\"ok\":\"该图片名称可以使用!\"}";
			} else {
				// 上传的文件名称已存在
				return "{\"error\":\"该图片名称已经存在!\"}";
			}
		} else {
			return "{\"ok\":\"\"}";
		}
	}

	void copy(File f1, File f2) {// f1 源文件路径 f2目标路径 最后把f2 insert 到数据库就不写了
		try {
			// 建立相关的字节输入流
			FileInputStream fr = new FileInputStream(f1); // 通过打开一个到实际文件的连接来创建一个
			// FileInputStream，该文件通过文件系统中的路径名

			// 创建一个向具有指定名称的文件中写入数据的输出文件流。
			FileOutputStream fw = new FileOutputStream(f2);
			byte buffer[] = new byte[1]; // 声明一个byte型的数组，数组的大小是512个字节
			while (fr.read(buffer) != -1) { // read()从此输入流中读取一个数据字节，只要读取的结果不！=-1就执行while循环中的语句块
				fw.write(buffer); // write(byte[] b)将 b.length
									// 个字节从指定字节数组写入此文件输出流中。
			}
			fw.close();// 关闭此文件输出流并释放与此流有关的所有系统资源。
			fr.close();
			logger.debug("文件" + f1.getName() + "里的内容已拷贝到文件" + f2.getName()
					+ "中！");
		} catch (IOException ioe) {
			logger.error(ioe.getMessage());
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
	}

	public void bcopy(File f1, File f2) {
		if (f1.exists()) {
			// 判断要拷贝的文件是否存在

			copy(f1, f2);// 调用copy方法
			logger.debug("上传文件相关的信息：（名字，路径，大小，最后修改的时间是：）");
			getinfo(f1);
			getinfo(f2);
			logger.debug("上传成功后文件相关的信息：（名字，路径，大小，最后修改的时间是：）");
		} else {
			logger.debug("要拷贝的文件不存在!");
		}
	}

	// 获取文件的一些信息
	private void getinfo(File f1) {
		// TODO Auto-generated method stub
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日hh时mm分ss秒");
		if (f1.isFile()) {// isFile()方法是测试此抽象路径名表示的文件是否是一个标准文件。
			logger.debug("文件名称：" + f1.getName());
			logger.debug("文件路径：" + f1.getAbsolutePath());
			logger.debug("文件大小：" + f1.length() + "字节(byte)");
			logger.debug("最后修改的时间是：" + sdf.format(new Date(f1.lastModified())));
		} else {
			logger.debug("上传成功后获取服务器的相关信息：");
			logger.debug("目录名称：" + f1.getName());
			logger.debug("文件路径：" + f1.getAbsolutePath());
			File[] files = f1.listFiles();
			logger.debug("此目录中有" + files.length + "个文件！");
		}
		logger.debug("_______________________________");
	}

	/**
	 * 截取图片
	 * 
	 * @param srcImageFile
	 *            原图片地址
	 * @param x
	 *            截取时的x坐标
	 * @param y
	 *            截取时的y坐标
	 * @param desWidth
	 *            截取的宽度
	 * @param desHeight
	 *            截取的高度
	 */
	public static void imgCut(String srcImageFile, int x, int y, int desWidth,
			int desHeight) {
		try {
			Image img;
			ImageFilter cropFilter;
			File f = new File(srcImageFile + "_src.jpg");
			BufferedImage bi = ImageIO.read(f);
			int srcWidth = bi.getWidth();
			int srcHeight = bi.getHeight();
			if (srcWidth >= desWidth && srcHeight >= desHeight) {
				Image image = bi.getScaledInstance(srcWidth, srcHeight,
						Image.SCALE_DEFAULT);
				cropFilter = new CropImageFilter(x, y, desWidth, desHeight);
				img = Toolkit.getDefaultToolkit().createImage(
						new FilteredImageSource(image.getSource(), cropFilter));
				BufferedImage tag = new BufferedImage(desWidth, desHeight,
						BufferedImage.TYPE_INT_RGB);
				Graphics g = tag.getGraphics();
				g.drawImage(img, 0, 0, null);
				g.dispose();
				// 输出文件
				ImageIO.write(tag, "JPEG", new File(srcImageFile + "_cut.jpg"));
				f.delete();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
